//index.js
const app = getApp()
const {
  $Toast
} = require('../../dist/base/index');
Page({
  data: {
    currentTabBar: 'index',
    word: '',
    contact: '',
    name: '',
    lastWord: '',
    chooseLeaveContact: true,
    current: '留名',
    leaveContact: [{
      id: '1',
      name: '留名'
    }, {
      id: '0',
      name: '算了'
    }]
  },
  onChange({
    detail = {}
  }) {
    this.setData({
      current: detail.value
    });
    if (detail.value === '留名') {
      this.setData({
        chooseLeaveContact: true
      });
    } else {
      this.setData({
        chooseLeaveContact: false
      });
    }
  },
  onLoad: function(options) {
    console.log(options)
    if(options.key == null || options.key == undefined){
      this.setData({
        currentTabBar: 'welcom'
      });
    }else{
      this.setData({
        currentTabBar: options.currentTabBar
      });
    }
    
  },
  formSubmit: function(e) {
    let that = this;
    if (that.data.word == '' || that.data.word == undefined) {
      $Toast({
        content: '啥都不写你提交啥',
        type: 'warning'
      });
      return;
    }
    if (that.data.lastWord == that.data.word) {
      $Toast({
        content: '留一次就行了',
        type: 'warning'
      });
      return;
    }
    $Toast({
      content: '提交中',
      type: 'loading'
    });
    const db = wx.cloud.database()
    db.collection('words').add({
      data: {
        word: that.data.word,
        name: that.data.name,
        contact: that.data.contact,
        createDate: new Date()
      },
      success: res => {
        $Toast.hide();
        $Toast({
          content: '留言成功,再见!',
          type: 'success'
        })
        this.setData({
          lastWord: that.data.word,
          word: '',
          name: '',
          contact: ''

        })

        console.log('[数据库] [新增记录] 成功，记录 _id: ', res._id)
      },
      fail: err => {
        $Toast({
          content: '留言失败!',
          type: 'error'
        })
        console.error('[数据库] [新增记录] 失败：', err)
      }
    })
  },
  formReset() {
    console.log('form发生了reset事件')
  },
  wordInput: function(event) {
    this.setData({
      word: event.detail.detail.value
    });
  },
  nameInput: function(event) {
    this.setData({
      name: event.detail.detail.value
    });
  },
  contactInput: function(event) {
    this.setData({
      contact: event.detail.detail.value
    });
  },
  handleChange({
    detail
  }) {
    if(detail.key == this.data.currentTabBar){
      return 
    }else{
      this.setData({
        currentTabBar: detail.key
      });
      wx.redirectTo({
        url: '../' + detail.key + '/' + detail.key + '?currentTabBar=' + detail.key
      })
    }
    
  },
})